package com.hbu.housingbrokerug.activities;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hbu.housingbrokeruganda.Parser.JSONParser;
import com.hbu.imagePackage.BaseActivity;
import com.hbu.imagePackage.ImagePagerActivity;
import com.hub.R;
/**
 * 
 * @author Lubwama Samuel
 *
 */
@SuppressWarnings("deprecation")
public class SingleUnit extends BaseActivity {
	TextView price,location,description,proximityTo;
	Gallery singleGallery;
	Button call,share,directions;
	
	String[] galleryData=null;
	String[] unitComposition;
	String[] nearTo;
	
	private ProgressDialog pDialog;
	parserFromUrl parser=new parserFromUrl();
	
	 private static final String TAG_SUCCESS_COMPOSITION = "success";
	 private static final String TAG_SUCCESS_GALLERY = "success";
	 private static final String TAG_SUCCESS_PROXIMITY = "success";
	
		@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_unit_item);      
    
    unitComposition=new String[]{};
    galleryData=new String[]{};
    nearTo=new String[]{};
   
    new getMoreData().execute();       
    
    Bundle bundle=getIntent().getExtras();
    try{
   	 if("success".equals(bundle.getString("FEEDBACK_STATUS").toString())){
  Toast.makeText(this, "Your FeedBack was Successfully recieved. Thank You!", Toast.LENGTH_LONG).show(); 		 
 }
 else{		 
	 Toast.makeText(this, "An Error Occued during submition of your FeedBack try again later"+bundle.getString("FEEDBACK_STATUS"), Toast.LENGTH_LONG).show();
   	 }
   	 
    }catch(Exception e){
   	 
    }
    
}
 @Override

 public boolean onCreateOptionsMenu(Menu menu) {
	getMenuInflater().inflate(R.menu.single_unit_item, menu);
	return true;
}

 public boolean onOptionsItemSelected(MenuItem item) {
	final Bundle bundle=getIntent().getExtras();
	switch (item.getItemId()) {
		case R.id.feed_back:
			startFeedBackPage(bundle);
			return true;
		case R.id.menu_item_share:
			shareWith();
			return true;
		case R.id.about_us:
		   startAboutActivity();
		   return true;   
		case R.id.menu_item_call:
			   callLandLord();
			   return true;		   
		case R.id.menu_item_getDirections:
			   getDirections();
			   return true;	
		default:
			return false;
	}
}

private void startAboutActivity() {
	Intent intent = new Intent(this, About.class);
	intent.putExtra("MESSAGE","");
	startActivity(intent);
}

private void startFeedBackPage(Bundle bundle) {
	// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),FeedBack.class);
intent.putExtra("UNIT_ID",bundle.getString("UNIT_ID"));
intent.putExtra("UNIT_DISTRICT",bundle.getString("UNIT_DISTRICT"));
intent.putExtra("UNIT_CITY",bundle.getString("UNIT_CITY"));
intent.putExtra("UNIT_TOWN",bundle.getString("UNIT_TOWN"));
intent.putExtra("UNIT_VILLAGE",bundle.getString("UNIT_VILLAGE"));
intent.putExtra("UNIT_LATITUDE",bundle.getString("UNIT_LATITUDE"));
intent.putExtra("UNIT_LONGITUDE",bundle.getString("UNIT_LONGITUDE"));
intent.putExtra("UNIT_CATEGORY",bundle.getString("UNIT_CATEGORY"));
intent.putExtra("UNIT_COST",bundle.getString("UNIT_COST"));
intent.putExtra("LANDLORD_FIRSTNAME",bundle.getString("LANDLORD_FIRSTNAME"));
intent.putExtra("LANDLORD_LASTNAME",bundle.getString("LANDLORD_LASTNAME"));
intent.putExtra("CONTACTS",bundle.getString("CONTACTS"));	
	startActivityForResult(intent, 100);	
	SingleUnit.this.finish();
}

 private void startImagePagerActivity(int position,String unit_id) {
		Intent intent = new Intent(this, ImagePagerActivity.class);
		intent.putExtra("UNIT_ID",unit_id);
		startActivity(intent);
	}
 

 
public class getMoreData extends AsyncTask<String, String, String> {
	parserFromUrl parser=new parserFromUrl();
	JSONParser urlRequest=new JSONParser();
	Bundle bundle=getIntent().getExtras();
	
	protected void onPreExecute() {
		super.onPreExecute();
		pDialog = new ProgressDialog(SingleUnit.this);
		pDialog.setMessage("Loading Houses From Server. Please wait...");
	pDialog.setIndeterminate(false);
	pDialog.setCancelable(false);
	pDialog.show();
}

@Override
protected String doInBackground(String... params) {
	
	// TODO Auto-generated method stub			
JSONObject json_gallery=urlRequest.makeHttpRequest(parser.getIpOrDomain()+"get_single_unit_gallery_data.php","GET"
, parser.getParametersSingleUnitGallery(bundle.getString("UNIT_ID")));	

JSONObject json_composition=urlRequest.makeHttpRequest(parser.getIpOrDomain()+"get_single_unit_composition_data.php","GET"
, parser.getParametersSingleUnitComposition(bundle.getString("UNIT_ID")));	


JSONObject json_proximityTo=urlRequest.makeHttpRequest(parser.getIpOrDomain()+"get_single_unit_proximityto_data.php","GET"
, parser.getParametersSingleUnitProximityTo(bundle.getString("UNIT_ID")));


Log.d("Perserlllllll",""+json_proximityTo);	
try{	
int  success_gallery = json_gallery.getInt(TAG_SUCCESS_GALLERY);
if(success_gallery==1){
 JSONArray jArray=json_gallery.getJSONArray("unit_gallery");	
 galleryData=new String[jArray.length()];

 for(int i=0;i<jArray.length();i++){	
	 
JSONObject json1=jArray.getJSONObject(i);
 
galleryData[i]=json1.getString("urls_image");
}
}
 else{ 
	 galleryData=new String[1];
	 galleryData[0]="No Data";
 }

}catch(Exception  e){
	Log.e("ERROR GETTING DATA TO ARRAY", e.toString());							
	}
	
	
try{	
	int  success_composition = json_composition.getInt(TAG_SUCCESS_COMPOSITION);
	if(success_composition==1){
	 JSONArray jArray=json_composition.getJSONArray("unit_composition");	
 unitComposition=new String[jArray.length()];
 for(int i=0;i<jArray.length();i++){	
JSONObject json1=jArray.getJSONObject(i);
unitComposition[i]=json1.getString("composition");
}
	 

		
    }
	 else{ 
		 unitComposition=new String[1];
		 unitComposition[0]=parser.getIpOrDomain()+parser.getDefaultImage();
	 }
	
}catch(Exception  e){
		Log.e("ERROR GETTING DATA TO COMPOSITION ARRAY", e.toString());	
unitComposition=new String[1];
 unitComposition[0]="No Data";				
}
	
	try{
		int  success_proximityto = json_proximityTo.getInt(TAG_SUCCESS_PROXIMITY);	
		if(success_proximityto==1){
		 JSONArray jArray=json_proximityTo.getJSONArray("unit_proximity_to");	
 nearTo=new String[jArray.length()];
 for(int i=0;i<jArray.length();i++){	
 JSONObject json1=jArray.getJSONObject(i);
 nearTo[i]=json1.getString("feature");
	}				
   }
	else{ 
			nearTo=new String[1];
			nearTo[0]="No Data";
 }

}catch(Exception  e1){
	Log.e("ERROR GETTING DATA TO PROXIMITY ARRAY ", e1.toString());									
nearTo=new String[1];
nearTo[0]="No Data";
		}				
	
	return null;
}
	
protected void onPostExecute(String file_url) {
	// dismiss the dialog after getting all products
pDialog.dismiss();

// updating UI from Background Thread
runOnUiThread(new Runnable() {
	public void run() {
		/**
 * Updating parsed JSON data into ListView
 * */	
	
if(galleryData[0]!="No Data" && unitComposition[0]!="No Data"  && nearTo[0]!="No Data")	{
price=(TextView) findViewById(R.id.price);
location=(TextView) findViewById(R.id.location);
description=(TextView) findViewById(R.id.description);
proximityTo=(TextView) findViewById(R.id.nearTo);
share=(Button) findViewById(R.id.share);
directions=(Button) findViewById(R.id.direction);
call=(Button) findViewById(R.id.call);

 price.setText("COST PER MONTH "+bundle.getString("UNIT_COST"));
 location.setText("CATEGORY\n"+bundle.getString("UNIT_CATEGORY")+"\n"+"LOCATION: "+"District:"+bundle.getString("UNIT_DISTRICT")+",City:"+bundle.getString("UNIT_CITY")
 +",Town:"+bundle.getString("UNIT_TOWN")+",Village:"+bundle.getString("UNIT_VILLAGE"));
 
//Getting Unit Composition
 try{
     String compositionLoopData="HOUSE DETAILS";
 for(int i=0;i<unitComposition.length;i++){
   compositionLoopData+=unitComposition[i];	   
 }
 description.setText(compositionLoopData);
  }
  catch(Exception e){
  	
  	Log.e("FAILED TO COVERT COMPOSITION", e+"");    	
    }   
 
 
 //Getting Unit Composition
   if(nearTo.length>0){
     try{
         String proximitytoLoopData="NEAR TO \n";
 for(int i=0;i<nearTo.length;i++){
  proximitytoLoopData+=nearTo[i];	   
 }
 proximityTo.setText(proximitytoLoopData);
}
  catch(Exception e){
  	
  	Log.e("FAILED TO COVERT Proximity To", e+"");    	
    }       
 }
 else{
	 proximityTo.setText("No features near to house specified");
     }
   Log.d("AMOUT OF DATA",""+nearTo.length);
     		         
if(galleryData[0]!="No Data"){	
singleGallery = (Gallery) findViewById(R.id.singleUnitGallery);
singleGallery.setAdapter(new ImageGalleryAdapterSingleUnit());
singleGallery.setOnItemClickListener(new OnItemClickListener() {
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		startImagePagerActivity(position, bundle.get("UNIT_ID").toString());
		}
	});
    
	
}else{	
	
	Intent intent = new Intent(SingleUnit.this,About.class);
    intent.putExtra("MESSAGE", "Failed");
    startActivity(intent);
}
			
  //setting calling function
  call.setOnClickListener(new OnClickListener() {

	@Override
	public void onClick(View arg0) {
		callLandLord();
	}
	  
  });

  //setting share function
  share.setOnClickListener(new OnClickListener() {	
	@Override
	public void onClick(View v) {
		shareWith();			
	}
});
  
 // setting get location function
          directions.setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View v) {
				getDirections();
			}
		});
}
		else{
			
			 AlertDialog alert = new AlertDialog.Builder(SingleUnit.this).create();
			 alert.setTitle("Error");
 alert.setMessage("You May have run out of Interenet Reach Please get to the Back To the HotSport Or Activate Data");
 alert.setButton("CLOSE APPLICATION", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
	// TODO Auto-generated method stub
						SingleUnit.this.finish();
					}
				});
				 alert.show();
				
			}
		}
		});
	}	

}

 private class ImageGalleryAdapterSingleUnit extends BaseAdapter {

		@Override
		public int getCount() {
			
			return galleryData.length;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
//Images to the Upper Gallery
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView = (ImageView) convertView;
			if (imageView == null) {
				imageView = (ImageView) getLayoutInflater().inflate(R.layout.item_gallery_image, parent, false);
			}
			imageLoader.displayImage(parser.getIpOrDomain()+galleryData[position], imageView,parser.getOptions() );
			

			return imageView;
		}
	}

  
 private void callLandLord(){
		final Bundle bundle=getIntent().getExtras();
		Intent callIntent = new Intent(Intent.ACTION_CALL);
		callIntent.setData(Uri.parse("tel:"+bundle.getString("CONTACTS")));

	startActivity(callIntent);
}

//Get Directions to the Location of the Premises
private void getDirections(){
		final Bundle bundle=getIntent().getExtras();
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
                Uri.parse("http://maps.google.com/maps?q=" +bundle.getString("UNIT_LATITUDE") + "," + bundle.getString("UNIT_LONGITUDE")));
            startActivity(intent);
}

//Share with a Friend the Housing option you Found
private void shareWith(){
			final Bundle bundle=getIntent().getExtras();
			String contentToShare="I found this Rental Option \n"+"  of Cost Per Month: "+bundle.getString("UNIT_COST")+
					"\n"+"Located in:"+"District:"+bundle.getString("UNIT_DISTRICT")+",City:"+bundle.getString("UNIT_CITY")
	        		 +",Town:"+bundle.getString("UNIT_TOWN")+",Village:"+bundle.getString("UNIT_VILLAGE")+" \nUsing Housing Broker Uganda. \n Try housing Broker Uganda \n http://hbu.com/apps/downloads";
			Intent sendIntent = new Intent();
			sendIntent.setAction(Intent.ACTION_SEND);
			sendIntent.putExtra(Intent.EXTRA_TEXT,contentToShare);
			sendIntent.setType("text/plain");
			startActivity(Intent.createChooser(sendIntent, getResources().getText(0, "Share Housing Facility to")));	
		} 
}